#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
修复MES系统中的语法错误
"""

import os
import re

def fix_foreign_key_syntax():
    """修复ForeignKey语法错误"""
    
    # 需要修复的文件和对应的错误行
    fixes = [
        ('apps/warehouse/models.py', 46, 
         'updated_by = ForeignKey(User, on_delete=models.CASCADE verbose_name=_("updated_by"))',
         'updated_by = ForeignKey(User, on_delete=models.CASCADE, verbose_name=_("updated_by"))'),
        
        ('apps/warehouse/models.py', 72, 
         'updated_by = ForeignKey(User, on_delete=models.CASCADE verbose_name=_("updated_by"))',
         'updated_by = ForeignKey(User, on_delete=models.CASCADE, verbose_name=_("updated_by"))'),
        
        ('apps/warehouse/models.py', 84, 
         'content_type = ForeignKey(ContentType, on_delete=models.CASCADE blank=True, null=True)',
         'content_type = ForeignKey(ContentType, on_delete=models.CASCADE, blank=True, null=True)'),
    ]
    
    for file_path, line_num, old_text, new_text in fixes:
        full_path = os.path.join(os.path.dirname(__file__), file_path)
        
        if not os.path.exists(full_path):
            print(f"文件不存在: {full_path}")
            continue
            
        try:
            with open(full_path, 'r', encoding='utf-8') as f:
                lines = f.readlines()
            
            # 检查并修复指定行
            if line_num <= len(lines):
                original_line = lines[line_num - 1].strip()
                if old_text in original_line:
                    lines[line_num - 1] = original_line.replace(old_text, new_text) + '\n'
                    print(f"修复 {file_path}:{line_num}")
                else:
                    # 如果不匹配，搜索整个文件
                    for i, line in enumerate(lines):
                        if old_text in line:
                            lines[i] = line.replace(old_text, new_text)
                            print(f"修复 {file_path}:{i+1}")
                            break
            
            # 写回文件
            with open(full_path, 'w', encoding='utf-8') as f:
                f.writelines(lines)
                
        except Exception as e:
            print(f"修复 {file_path} 时出错: {e}")

def fix_all_foreign_key_syntax():
    """批量修复所有ForeignKey语法错误"""
    
    # 通用的正则表达式匹配模式
    patterns = [
        # 匹配缺少逗号的ForeignKey
        (r'(on_delete=models\.CASCADE)\s+(verbose_name=)', r'\1, \2'),
        (r'(on_delete=models\.CASCADE)\s+(blank=True)', r'\1, \2'),
        (r'(on_delete=models\.CASCADE)\s+(null=True)', r'\1, \2'),
        (r'(on_delete=models\.CASCADE)\s+(related_name=)', r'\1, \2'),
        (r'(on_delete=models\.CASCADE)\s+(unique=True)', r'\1, \2'),
        
        # 其他缺少逗号的情况
        (r'(blank=True)\s+(null=True)', r'\1, \2'),
        (r'(null=True)\s+(verbose_name=)', r'\1, \2'),
        (r'(null=True)\s+(related_name=)', r'\1, \2'),
        (r'(related_name="[^"]*")\s+(verbose_name=)', r'\1, \2'),
        (r'(related_name="[^"]*")\s+(blank=True)', r'\1, \2'),
        (r'(unique=True)\s+(verbose_name=)', r'\1, \2'),
    ]
    
    # 遍历所有Python文件
    for root, dirs, files in os.walk('apps'):
        for file in files:
            if file.endswith('.py'):
                file_path = os.path.join(root, file)
                
                try:
                    with open(file_path, 'r', encoding='utf-8') as f:
                        content = f.read()
                    
                    original_content = content
                    
                    # 应用所有修复模式
                    for pattern, replacement in patterns:
                        content = re.sub(pattern, replacement, content)
                    
                    # 如果内容有变化，写回文件
                    if content != original_content:
                        with open(file_path, 'w', encoding='utf-8') as f:
                            f.write(content)
                        print(f"修复了 {file_path}")
                        
                except Exception as e:
                    print(f"处理 {file_path} 时出错: {e}")

if __name__ == '__main__':
    print("=== 修复MES系统语法错误 ===")
    fix_all_foreign_key_syntax()
    print("=== 修复完成 ===") 